// 软删除通用工具函数
const db = uniCloud.database()
const dbCmd = db.command

/**
 * 软删除记录
 * @param {string} collection - 集合名称
 * @param {string} id - 记录ID
 * @param {string} userId - 删除人ID
 * @param {string} reason - 删除原因（可选）
 * @returns {Object} 删除结果
 */
async function softDelete(collection, id, userId, reason = '') {
	try {
		const result = await db.collection(collection)
			.doc(id)
			.update({
				is_deleted: true,
				deleted_at: Date.now(),
				deleted_by: userId,
				delete_reason: reason
			})
		
		return {
			code: 200,
			message: '已移至回收站',
			data: { updated: result.updated }
		}
	} catch (err) {
		console.error(`[softDelete] 软删除失败 - ${collection}/${id}:`, err)
		return {
			code: 500,
			message: err.message || '删除失败',
			data: null
		}
	}
}

/**
 * 批量软删除
 * @param {string} collection - 集合名称
 * @param {Array} ids - 记录ID数组
 * @param {string} userId - 删除人ID
 * @param {string} reason - 删除原因（可选）
 * @returns {Object} 删除结果
 */
async function batchSoftDelete(collection, ids, userId, reason = '') {
	try {
		let successCount = 0
		let failCount = 0
		
		for (const id of ids) {
			try {
				await db.collection(collection)
					.doc(id)
					.update({
						is_deleted: true,
						deleted_at: Date.now(),
						deleted_by: userId,
						delete_reason: reason
					})
				successCount++
			} catch (err) {
				console.error(`批量软删除失败 - ${id}:`, err)
				failCount++
			}
		}
		
		return {
			code: 200,
			message: `成功删除${successCount}条，失败${failCount}条`,
			data: { success: successCount, failed: failCount }
		}
	} catch (err) {
		console.error('[batchSoftDelete] 批量软删除失败:', err)
		return {
			code: 500,
			message: err.message || '批量删除失败',
			data: null
		}
	}
}

/**
 * 恢复软删除的记录
 * @param {string} collection - 集合名称
 * @param {string} id - 记录ID
 * @returns {Object} 恢复结果
 */
async function restoreRecord(collection, id) {
	try {
		const result = await db.collection(collection)
			.doc(id)
			.update({
				is_deleted: false,
				deleted_at: dbCmd.remove(),
				deleted_by: dbCmd.remove(),
				delete_reason: dbCmd.remove()
			})
		
		return {
			code: 200,
			message: '恢复成功',
			data: { updated: result.updated }
		}
	} catch (err) {
		console.error(`[restoreRecord] 恢复失败 - ${collection}/${id}:`, err)
		return {
			code: 500,
			message: err.message || '恢复失败',
			data: null
		}
	}
}

/**
 * 批量恢复
 * @param {string} collection - 集合名称
 * @param {Array} ids - 记录ID数组
 * @returns {Object} 恢复结果
 */
async function batchRestore(collection, ids) {
	try {
		let successCount = 0
		let failCount = 0
		
		for (const id of ids) {
			try {
				await db.collection(collection)
					.doc(id)
					.update({
						is_deleted: false,
						deleted_at: dbCmd.remove(),
						deleted_by: dbCmd.remove(),
						delete_reason: dbCmd.remove()
					})
				successCount++
			} catch (err) {
				console.error(`批量恢复失败 - ${id}:`, err)
				failCount++
			}
		}
		
		return {
			code: 200,
			message: `成功恢复${successCount}条，失败${failCount}条`,
			data: { success: successCount, failed: failCount }
		}
	} catch (err) {
		console.error('[batchRestore] 批量恢复失败:', err)
		return {
			code: 500,
			message: err.message || '批量恢复失败',
			data: null
		}
	}
}

/**
 * 永久删除（物理删除）
 * @param {string} collection - 集合名称
 * @param {string} id - 记录ID
 * @returns {Object} 删除结果
 */
async function permanentlyDelete(collection, id) {
	try {
		await db.collection(collection).doc(id).remove()
		
		return {
			code: 200,
			message: '永久删除成功',
			data: null
		}
	} catch (err) {
		console.error(`[permanentlyDelete] 永久删除失败 - ${collection}/${id}:`, err)
		return {
			code: 500,
			message: err.message || '永久删除失败',
			data: null
		}
	}
}

/**
 * 批量永久删除
 * @param {string} collection - 集合名称
 * @param {Array} ids - 记录ID数组
 * @returns {Object} 删除结果
 */
async function batchPermanentlyDelete(collection, ids) {
	try {
		let successCount = 0
		let failCount = 0
		
		for (const id of ids) {
			try {
				await db.collection(collection).doc(id).remove()
				successCount++
			} catch (err) {
				console.error(`批量永久删除失败 - ${id}:`, err)
				failCount++
			}
		}
		
		return {
			code: 200,
			message: `成功删除${successCount}条，失败${failCount}条`,
			data: { success: successCount, failed: failCount }
		}
	} catch (err) {
		console.error('[batchPermanentlyDelete] 批量永久删除失败:', err)
		return {
			code: 500,
			message: err.message || '批量永久删除失败',
			data: null
		}
	}
}

/**
 * 获取软删除的记录列表
 * @param {string} collection - 集合名称
 * @param {number} pageNum - 页码
 * @param {number} pageSize - 每页数量
 * @returns {Object} 查询结果
 */
async function getDeletedRecords(collection, pageNum = 1, pageSize = 20) {
	try {
		const skip = (pageNum - 1) * pageSize
		
		// 查询总数
		const countRes = await db.collection(collection)
			.where({ is_deleted: true })
			.count()
		
		// 查询数据
		const res = await db.collection(collection)
			.where({ is_deleted: true })
			.orderBy('deleted_at', 'desc')
			.skip(skip)
			.limit(pageSize)
			.get()
		
		return {
			code: 200,
			message: '查询成功',
			data: {
				list: res.data || [],
				total: countRes.total || 0,
				pageNum,
				pageSize
			}
		}
	} catch (err) {
		console.error(`[getDeletedRecords] 查询失败 - ${collection}:`, err)
		return {
			code: 500,
			message: err.message || '查询失败',
			data: null
		}
	}
}

/**
 * 统计各表的软删除数据量
 * @returns {Object} 统计结果
 */
async function getDeletedStats() {
	try {
		const tables = [
			'dh-hospitals', 'dh-doctors', 'dh-nurses', 'dh-staff_users',
			'dh-patients', 'dh-services', 'dh-products', 'dh-doctor_schedules',
			'dh-appointments', 'dh-medical_records', 'dh-reviews', 
			'dh-consultations', 'dh-income_records', 'dh-leave_requests',
			'dh-purchase_requests', 'dh-inventory', 'dh-inventory_logs',
			'dh-hospital_promotions', 'dh-hospital_banners', 
			'dh-promotion_rules', 'dh-medical_authorizations'
		]
		
		const stats = {}
		let total = 0
		
		// 并行查询所有表的软删除数据量
		const results = await Promise.all(
			tables.map(tableName => 
				db.collection(tableName)
					.where({ is_deleted: true })
					.count()
			)
		)
		
		tables.forEach((tableName, index) => {
			const count = results[index].total || 0
			stats[tableName] = count
			total += count
		})
		
		return {
			code: 200,
			message: '统计成功',
			data: {
				total,
				stats
			}
		}
	} catch (err) {
		console.error('[getDeletedStats] 统计失败:', err)
		return {
			code: 500,
			message: err.message || '统计失败',
			data: null
		}
	}
}

module.exports = {
	softDelete,
	batchSoftDelete,
	restoreRecord,
	batchRestore,
	permanentlyDelete,
	batchPermanentlyDelete,
	getDeletedRecords,
	getDeletedStats
}

